import historyStore from '@/store/history';
import { createStoreBindings } from '@/miniprogram_npm/mobx-miniprogram-bindings/index';

import tools from '@/utils/tools';
import { loadHistoricalRecords, deleteRecord } from '@/service/api/history';

import Dialog from 'tdesign-miniprogram/dialog/index';
import Message from 'tdesign-miniprogram/message/index';
const messageDefaultConfig = (content) => {
    return {
        context: this,
        offset: [60, 32],
        content: content
    };
};

Page({
    data: {
        pageNumber: 1,
        pageSize: 20
    },

    onLoad() {
        this.storeBindings = createStoreBindings(this, {
            store: historyStore,
            fields: ['records', 'loadFinished'],
            actions: ['deleteRecord', 'resetAll']
        });
    },

    onUnload() {
        this.storeBindings.destroyStoreBindings();
    },

    onReady: async function () {
        try {
            this.resetAll();
            await loadHistoricalRecords();
        } catch (err) {
            Message.error(messageDefaultConfig(err.message));
        }
    },

    // 下拉刷新时间
    onPullDownRefresh: tools.throttle(async function () {
        try {
            this.resetAll();
            await loadHistoricalRecords();
        } catch (err) {
            Message.error(messageDefaultConfig(err.message));
        }
    }, 5000),

    // 上滑触底刷新事件
    onReachBottom: tools.throttle(async function () {
        try {
            if (this.data.loadFinished) {
                return;
            }
            await loadHistoricalRecords();
        } catch (err) {
            Message.error(messageDefaultConfig(err.message));
        }
    }, 1000),

    // 查看文件详情事件
    jumpToFileDetail(e) {
        const path = e.currentTarget.dataset.filepath;
        wx.navigateTo({
            url: '/pages/history/detail/index?path=' + path
        });
    },

    // 删除预测记录
    handleDeleteRecord(e) {
        Dialog.confirm({
            title: '警告',
            content: '是否删除这条记录？',
            confirmBtn: '确定',
            cancelBtn: '取消'
        })
            .then(async () => {
                await deleteRecord(e.currentTarget.dataset.id);
                this.deleteRecord(e.currentTarget.dataset.id)
                Message.success(messageDefaultConfig('删除成功'));
            })
            .catch((err) => {
                if (Object.keys(err).includes('trigger')) return;
                Message.error(messageDefaultConfig(err.message));
            });
    }
});
